package game.module.mail.dao;

import java.io.File;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

import game.module.template.MailTemplate;
import lion.common.Reloadable;

public class MailTemplateCache implements Reloadable {

	private static Logger logger = LoggerFactory.getLogger(MailTemplateCache.class);

	static class SingletonHolder {
		static MailTemplateCache instance = new MailTemplateCache();
	}

	public static MailTemplateCache getInstance() {
		return SingletonHolder.instance;
	}

	private volatile List<MailTemplate> templateList;

	private static Map<Integer, MailTemplate> map_all = new ConcurrentHashMap<>();

	private static Map<Integer, MailTemplate> wait_send_map = new ConcurrentHashMap<>();

	@Override
	public void reload() {
		try {
			String jsonStr = Files.asCharSource(new File("data/mail.json"), Charset.forName("UTF-8")).read();
			ObjectMapper mapper = new ObjectMapper();
			templateList = mapper.readValue(jsonStr, new TypeReference<List<MailTemplate>>() {
			});
			logger.info("size={}", templateList.size());
		} catch (Exception e) {
			logger.error("", e);
		}
		if (this.templateList == null) {
			return;
		}
		long now = System.currentTimeMillis();
		for (MailTemplate mt : templateList) {
			map_all.put(mt.getId(), mt);
			if (mt.getSendTimeSec() > 0 && mt.getSendTimeSec() > now) {
				wait_send_map.put(mt.getId(), mt);
			}
		}

	}

	public MailTemplate getMailTemplateById(int templateId) {
		return map_all.get(templateId);
	}

}
